package com.waitingsnow.core.display.player
{
import com.waitingsnow.core.debug.Logger;
import com.waitingsnow.core.display.loader.BaseLoader;

import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.system.ApplicationDomain;

/**
 * 
 * @author waitingsnow
 * $Id: SwfPlayer.as 2 2012-05-17 10:10:03Z cgslendy@gmail.com $
 */
public class SwfPlayer extends Sprite
{
	//==========================================================================
	//  Constructor
	//==========================================================================
	/**
	 * Constructs a new <code>SwfPlayer</code> instance.
	 * 
	 */
	public function SwfPlayer()
	{
	}
	
	//==========================================================================
	//  Variables
	//==========================================================================
	private var baseLoader:BaseLoader;
	private var mc:MovieClip;
	private var info:LoaderInfo;
	private var _w:int = 500;
	private var _h:int = 400;
	
	//==========================================================================
	//  Methods
	//==========================================================================
	public function startPlay(url:String, domin:ApplicationDomain = null, checkPolice:Boolean = false):void
	{
		if (!baseLoader)
		{
			baseLoader = new BaseLoader();
			baseLoader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
		}
		baseLoader.startLoad(url, domin, checkPolice);
	}
	
	public function setSize(w:int, h:int):void
	{
		_w = w;
		_h = h;
		if (mc)
		{
			width = _w * mc.width / info.width;
			height = _h * mc.height / info.height;
		}
	}
	
	public function dispose():void
	{
		if (baseLoader)
		{
			baseLoader.dispose();
			baseLoader = null;
		}
	}
	
	//==========================================================================
	//  Event Handlers
	//==========================================================================
	private function loaderCompleteHandler(event:Event):void
	{
		baseLoader.removeEventListener(Event.COMPLETE, loaderCompleteHandler);
		var loader:Loader = baseLoader.getLoader();
		info = loader.contentLoaderInfo;
		mc = MovieClip(loader.content);
		mc.gotoAndPlay(1);
		mc.addEventListener(Event.ENTER_FRAME, mcEnterFrameHandler);
		addChild(mc);
		setSize(_w, _h);
		dispatchEvent(new Event(Event.INIT));
	}
	
	private function mcEnterFrameHandler(event:Event):void
	{
		if (mc.currentFrame == mc.totalFrames)
		{
			mc.stop();
			mc.removeEventListener(Event.ENTER_FRAME, mcEnterFrameHandler);
			dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}
}